<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="18">
				<div class="layout-padding-auto layout-padding-view">
					<el-input prefix-icon="search" v-model="filterText" placeholder="请输入关键字搜索" class="mb-2" />
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							:filter-node-method="filterNode"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<div class="w-full flex justify-between items-start h-[50px]">
						<el-form :model="form" ref="dataFormRef" :inline="true" @keyup.enter="getDataList" :rules="dataRules" v-loading="loading">
							<el-form-item prop="deviceId" label="设备">
								<el-select placeholder="请选择设备" v-model="form.deviceId" size="small" filterable @change="getDataList">
									<el-option v-for="item in deviceList" :key="item.id" :value="item.id" :label="item.name" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button icon="search" type="primary" class="ml-2" size="small" @click="getDataList">查询</el-button>
							</el-form-item>
						</el-form>
						<div class="flex items-center flex-nowrap">
							<div
								v-for="item in level"
								:key="item.pollutionDegree"
								:style="{ backgroundColor: item.color }"
								class="text-xs text-center p-1 min-w-[60px]"
							>
								{{ item.label }}
							</div>
						</div>
					</div>
					<div class="h-[calc(100%-60px)]">
						<FullCalendar class="h-full" :options="calendarOptions" ref="FullCalendarRef">
							<template v-slot:eventContent="arg">
								<el-tooltip placement="top">
									<template #content>
										<div class="w-[280px]">
											<div class="flex">
												<span class="w-[60px] min-w-[60px]">污染等级：</span>
												<div>{{ arg.event.title }}</div>
											</div>
											<div class="flex mt-1">
												<span class="w-[60px] min-w-[60px]">影响：</span>
												<div>{{ arg.event.extendedProps.influence }}</div>
											</div>
											<div class="flex mt-1">
												<span class="w-[60px] min-w-[60px]">措施：</span>
												<div>{{ arg.event.extendedProps.measures }}</div>
											</div>
										</div>
									</template>
									<div class="w-full py-1 text-xs cursor-pointer">{{ arg.event.title }}</div>
								</el-tooltip>
							</template>
						</FullCalendar>
					</div>
				</div>
			</pane>
		</splitpanes>
	</div>
</template>

<script setup lang="ts" name="pollutionCalendar">
import { watch } from 'vue';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import multiMonthPlugin from '@fullcalendar/multimonth';
import { TreeType, optionType } from '../pollutionAnalysis/data';
import { handleTree } from '/@/utils/other';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { fetchListByTag } from '/@/api/platform/airMonitorEquipment';
import { fetchList } from '/@/api/platform/trendAnalysis';
import { useMessage } from '/@/hooks/message';
import { level } from '../pollutionAnalysis/data';
const loading = ref(false);
const FullCalendarRef = ref();
const calendarOptions = reactive({
	plugins: [dayGridPlugin, multiMonthPlugin],
	// buttonText: {
	// 	today: '今年',
	// },
	headerToolbar: {
		right: 'getToYear getPrevYear getNextYear',
		left: 'title',
	},
	customButtons: {
		getPrevYear: {
			text: '上一年',
			click: getPrevYearApi,
		},
		getNextYear: {
			text: '下一年',
			click: getNextYearApi,
		},
		getToYear: {
			text: '今年',
			click: getToYearApi,
		},
	},
	locale: 'zh-cn',
	initialView: 'multiMonthYear',
	editable: false,
	selectable: false,
	selectMirror: false,
	dayMaxEvents: false,
	weekends: true,
	eventDisplay: 'block',
	events: [],
});
function getPrevYearApi() {
	unref(FullCalendarRef).getApi().prevYear();
	formatFormDate();
}
function getNextYearApi() {
	unref(FullCalendarRef).getApi().nextYear();
	formatFormDate();
}
function getToYearApi() {
	unref(FullCalendarRef).getApi().today();
	formatFormDate();
}
function formatFormDate() {
	const activeRange = unref(FullCalendarRef).getApi().currentData.dateProfile.activeRange;
	form.startYear = new Date(activeRange.start).getFullYear() + '-01-01 00:00:00';
	form.endYear = new Date(activeRange.end).getFullYear() + '-01-01 00:00:00';
	getDataList();
}
// 区域树使用的数据
const treeData = reactive({
	list: [] as TreeType[],
	defaultProps: {
		label: 'name',
	},
});
// 定义变量内容
const deviceList = ref<optionType[]>([]);
const dataFormRef = ref();
const treeRef = ref();
const filterText = ref('');
const siteId = ref();
const form = reactive({
	deviceId: '',
	startYear: '2023-01-01 00:00:00',
	endYear: '2024-01-01 00:00:00',
});
// 定义校验规则
const dataRules = ref({
	deviceId: [{ required: true, message: '请选择', trigger: 'change' }],
});
// 搜索树监听
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	getDeviceList();
};
const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDeviceList();
			nextTick(() => {
				unref(treeRef)?.setCurrentKey(siteId.value, true);
			});
		}
	});
};
const filterNode = (value: string, data: TreeType) => {
	if (!value) return true;
	return data.name.includes(value);
};
// 树节点查找设备
const getDeviceList = () => {
	fetchListByTag({ tag: unref(siteId) }).then((res) => {
		deviceList.value = res.data;
		if (res.data.length) {
			form.deviceId = res.data[0].id;
			getDataList();
		} else {
			form.deviceId = '';
		}
	});
};

const getDataList = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	try {
		loading.value = true;
		const res = await fetchList({ dt0: form.startYear, dt1: form.endYear, tp: 'DailyAvg', monitorEquipmentIds: [form.deviceId] });
		calendarOptions.events =
			res?.data[0]?.list?.map((d) => {
				const l = level.find((f) => f.pollutionDegree === d.pollutionDegree);
				return {
					start: d.recordData,
					title: d.degree,
					textColor: '#000',
					color: '#000',
					backgroundColor: l?.color,
					borderColor: l?.color,
					influence: l?.influence,
					measures: l?.measures,
				};
			}) || [];
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
onMounted(() => {
	getTreeDate();
});
</script>

<style lang="scss" scoped>
:deep(.fc-daygrid-event-harness) {
	visibility: visible !important;
}
</style>
